#include <QMap>
#include <QTcpSocket>
#include <QDebug>
#include <QThread>
#include <QCoreApplication>

#include "TcpServer.hpp"
#include "Client.hpp"

TcpServer::TcpServer(QObject *parent) :
    QTcpServer(parent)
{
}

void TcpServer::incomingConnection(int handle)
{
    Client *client = new Client(handle);
    m_clients.insert(handle, client);
    addPendingConnection(client->socket());

    connect(client, SIGNAL(disconnected()),
            this, SLOT(onDisconnected()));
    connect(client, SIGNAL(query(QString&,quint32,COMMAND)),
            databaseInstance(), SLOT(execQuery(QString&,quint32,COMMAND)));
    connect(databaseInstance(), SIGNAL(resultQuery(QSqlQuery,quint32,COMMAND)),
            client, SLOT(queryAnswer(QSqlQuery,quint32,COMMAND)));

    qDebug() << "New client was added, socket = "
             << handle;


}

void TcpServer::onDisconnected()
{
    Client* client =
            qobject_cast<Client*>(sender());
    int handle = client->socketDescriptor();
    qDebug() << "Socket" << handle
             << "will be removed";
    client->deleteLater();
    m_clients.remove(handle);
}

